'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { AuthApi, setTokenLocal, type OAuthProviders } from '@/lib/api';
import Link from 'next/link';

type ExchangeState = 'idle' | 'exchanging' | 'done' | 'error';

export default function LoginPage() {
  const router = useRouter();
  const search = useSearchParams();

  const [providers, setProviders] = useState<OAuthProviders | null>(null);
  const [loadingProviders, setLoadingProviders] = useState(true);

  const [expandPwd, setExpandPwd] = useState(false);
  const [captcha, setCaptcha] = useState<{ id: string; img: string; expire: number } | null>(null);

  const [login, setLogin] = useState('');
  const [password, setPassword] = useState('');
  const [captchaCode, setCaptchaCode] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);

  const [exchangeState, setExchangeState] = useState<ExchangeState>('idle');
  const [exchangeError, setExchangeError] = useState<string | null>(null);

  // Load available OAuth providers
  useEffect(() => {
    let mounted = true;
    (async () => {
      const res = await AuthApi.oauthProviders();
      if (!mounted) return;
      if (res.ok) {
        setProviders(res.data);
      }
      setLoadingProviders(false);
    })();
    return () => {
      mounted = false;
    };
  }, []);

  // If returning from OAuth with ?code&state, exchange token automatically
  useEffect(() => {
    const code = search.get('code');
    const state = search.get('state');
    if (!code || !state || exchangeState !== 'idle') return;

    const provider = sessionStorage.getItem('oauth_provider') || 'github';
    const savedState = sessionStorage.getItem('oauth_state');

    if (savedState && savedState !== state) {
      setExchangeState('error');
      setExchangeError('OAuth 状态不匹配，请重试。');
      return;
    }

    const redirectUri = window.location.origin + '/login';

    (async () => {
      setExchangeState('exchanging');
      const exec = async () => {
        if (provider === 'gitee') {
          return await AuthApi.giteeExchange({ code, redirectUri });
        }
        return await AuthApi.githubExchange({ code, redirectUri });
      };

      const res = await exec();
      if (!res.ok) {
        setExchangeState('error');
        setExchangeError(res.error.message || 'OAuth 登录失败');
        return;
      }

      setTokenLocal(res.data.token);
      // 清理缓存标记
      sessionStorage.removeItem('oauth_provider');
      sessionStorage.removeItem('oauth_state');
      setExchangeState('done');

      // 跳转到用户默认路由
      const to = res.data.user.defaultRoute || '/';
      router.replace(to);
    })();
  }, [search, exchangeState, router]);

  // Expand password section - fetch captcha initially
  useEffect(() => {
    if (!expandPwd || captcha) return;
    void refreshCaptcha();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [expandPwd]);

  const canUseGitHub = useMemo(() => !!providers?.github, [providers]);
  const canUseGitee = useMemo(() => !!providers?.gitee, [providers]);

  async function refreshCaptcha() {
    const res = await AuthApi.captcha();
    if (res.ok) {
      setCaptcha({
        id: res.data.captchaId,
        img: res.data.imageBase64,
        expire: res.data.expireSeconds,
      });
      setCaptchaCode('');
    } else {
      setFormError(res.error.message || '获取验证码失败');
    }
  }

  async function onSubmitPwd(e: React.FormEvent) {
    e.preventDefault();
    setFormError(null);

    if (!login || !password) {
      setFormError('请输入账号与密码');
      return;
    }
    if (!captcha?.id || !captchaCode) {
      setFormError('请输入验证码');
      return;
    }

    setSubmitting(true);
    const res = await AuthApi.login({
      login,
      password,
      captchaId: captcha.id,
      captchaCode,
    });
    setSubmitting(false);

    if (!res.ok) {
      setFormError(res.error.message || '登录失败');
      // 失败后刷新验证码以防止重放
      void refreshCaptcha();
      return;
    }

    // 持久化 Token 并跳转
    setTokenLocal(res.data.token);
    const to = res.data.user.defaultRoute || '/';
    router.replace(to);
  }

  function onOAuth(provider: 'github' | 'gitee') {
    setExchangeError(null);
    setExchangeState('idle');

    (async () => {
      const start = provider === 'gitee' ? await AuthApi.giteeStart() : await AuthApi.githubStart();
      if (!start.ok) {
        setExchangeState('error');
        setExchangeError(start.error.message || '无法开始第三方登录');
        return;
      }
      // 保存 provider 和 state，返回后用于校验与选择 exchange API
      sessionStorage.setItem('oauth_provider', provider);
      sessionStorage.setItem('oauth_state', start.data.state);
      window.location.href = start.data.url;
    })();
  }

  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center py-10 px-4">
      <div className="w-full max-w-[520px]">
        <div className="rounded-xl border bg-white p-6 shadow-sm dark:bg-neutral-950">
          <div className="mb-6">
            <h1 className="text-2xl font-semibold">登录 Hamster Docs</h1>
            <p className="text-sm text-fd-muted-foreground mt-1">
              使用第三方账号快速登录，或展开使用账号密码登录。
            </p>
          </div>

          {exchangeState === 'exchanging' && (
            <div className="mb-4 rounded-md bg-fd-accent px-3 py-2 text-sm">
              正在完成第三方登录，请稍候...
            </div>
          )}
          {exchangeState === 'error' && exchangeError && (
            <div className="mb-4 rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
              {exchangeError}
            </div>
          )}

          <div className="grid gap-3">
            <button
              type="button"
              className="inline-flex h-10 items-center justify-center rounded-md border px-4 text-sm font-medium transition-colors hover:bg-fd-accent disabled:opacity-50"
              onClick={() => onOAuth('github')}
              disabled={loadingProviders || !canUseGitHub}
            >
              使用 GitHub 登录
            </button>

            <button
              type="button"
              className="inline-flex h-10 items-center justify-center rounded-md border px-4 text-sm font-medium transition-colors hover:bg-fd-accent disabled:opacity-50"
              onClick={() => onOAuth('gitee')}
              disabled={loadingProviders || !canUseGitee}
            >
              使用 Gitee 登录
            </button>
          </div>

          <div className="my-6 flex items-center gap-3 text-sm text-fd-muted-foreground">
            <div className="h-[1px] flex-1 bg-fd-muted" />
            <span>或</span>
            <div className="h-[1px] flex-1 bg-fd-muted" />
          </div>

          {!expandPwd ? (
            <button
              type="button"
              className="inline-flex h-10 w-full items-center justify-center rounded-md border px-4 text-sm font-medium transition-colors hover:bg-fd-accent"
              onClick={() => setExpandPwd(true)}
            >
              使用账号密码登录
            </button>
          ) : (
            <form onSubmit={onSubmitPwd} className="grid gap-4">
              {formError && (
                <div className="rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
                  {formError}
                </div>
              )}

              <div className="grid gap-2">
                <label className="text-sm font-medium">账号（用户名或邮箱）</label>
                <input
                  className="h-10 w-full rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-fd-primary"
                  value={login}
                  onChange={(e) => setLogin(e.target.value)}
                  placeholder="username 或 email"
                  autoComplete="username"
                />
              </div>

              <div className="grid gap-2">
                <label className="text-sm font-medium">密码</label>
                <input
                  type="password"
                  className="h-10 w-full rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-fd-primary"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="********"
                  autoComplete="current-password"
                />
              </div>

              <div className="grid gap-2">
                <label className="text-sm font-medium">验证码</label>
                <div className="flex items-center gap-3">
                  <input
                    className="h-10 flex-1 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-fd-primary"
                    value={captchaCode}
                    onChange={(e) => setCaptchaCode(e.target.value)}
                    placeholder="请输入验证码"
                  />
                  {captcha ? (
                    <button
                      type="button"
                      className="rounded-md border px-2.5 py-1.5 text-xs hover:bg-fd-accent"
                      onClick={refreshCaptcha}
                      title="刷新验证码"
                    >
                      刷新
                    </button>
                  ) : null}
                </div>
                {captcha && (
                  <div className="mt-2">
                    <img
                      src={captcha.img}
                      alt="验证码"
                      className="h-12 rounded-md border bg-white"
                    />
                    <p className="mt-1 text-xs text-fd-muted-foreground">
                      验证码有效期 {captcha.expire}s
                    </p>
                  </div>
                )}
              </div>

              <button
                type="submit"
                className="inline-flex h-10 items-center justify-center rounded-md bg-fd-primary px-4 text-sm font-medium text-fd-primary-foreground hover:opacity-90 disabled:opacity-50"
                disabled={submitting}
              >
                {submitting ? '登录中...' : '登录'}
              </button>

              <div className="mt-1 text-xs text-fd-muted-foreground">
                忘记密码？请联系管理员重置。
              </div>
            </form>
          )}

          <div className="mt-6 text-xs text-fd-muted-foreground">
            返回{' '}
            <Link href="/" className="underline hover:text-fd-foreground">
              首页
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}